package com.bytz.modules.cms.reseller.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.common.exception.BytzBootException;
import com.bytz.common.util.mentity.EntityMergeInfoV2;
import com.bytz.common.util.mentity.util.MergeEntityOptions;
import com.bytz.common.util.mentity.util.MergeEntityUtil;
import com.bytz.modules.cms.reseller.constant.ResellerConstant;
import com.bytz.modules.cms.reseller.entity.EndUser;
import com.bytz.modules.cms.reseller.entity.ResellerEndUser;
import com.bytz.modules.cms.reseller.mapper.EndUserMapper;
import com.bytz.modules.cms.reseller.model.EndUserModel;
import com.bytz.modules.cms.reseller.model.ResellerModel;
import com.bytz.modules.cms.reseller.service.IEndUserService;
import com.bytz.modules.cms.reseller.service.IResellerEndUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 莱宝CMS—经销商管理—终端用户基本信息表（同步c4c） 服务实现类
 * </p>
 *
 * @author KyleWang
 * @since 2022-10-10
 */
@Service
public class EndUserServiceImpl extends ServiceImpl<EndUserMapper, EndUser> implements IEndUserService {

    @Autowired
    private IResellerEndUserService resellerEndUserService;

    @Override
    public List<EndUser> getByIds(Collection<String> ids) {

        if (CollectionUtils.isEmpty(ids)) {

            return new ArrayList<>();
        }

        return lambdaQuery().in(EndUser::getId, ids).list();
    }

    @Override
    public List<EndUser> getByCustomerName(String condition) {

        return lambdaQuery()
                .like(EndUser::getCustomerNumber, condition).or()
                .like(EndUser::getCustomerName, condition).or()
                .like(EndUser::getAddress, condition)
                .list();
    }

    @Override
    public List<EndUserModel> getByResellerId(String resellerId, String type) {

        List<ResellerEndUser> resellerEndUsers = resellerEndUserService.getByResellerId(resellerId, type);

        Map<String, List<ResellerEndUser>> endUserIdMap = resellerEndUsers.stream()
                .collect(Collectors.groupingBy(ResellerEndUser::getEndUserId));

        List<EndUserModel> endUserModels = BeanUtil.copyToList(getByIds(endUserIdMap.keySet()), EndUserModel.class);

        endUserModels.forEach(model -> {

            List<ResellerEndUser> group = endUserIdMap.get(model.getId());

            if (group.stream().anyMatch( e -> ObjectUtil.equals(e.getType(), ResellerConstant.ResellerEndUserType.SOLD_TO))) {

                model.setType(ResellerConstant.ResellerEndUserType.SOLD_TO);
            }
        });

        return endUserModels;
    }

    @Override
    public void saveSoldToByResellerModel(ResellerModel saveRo) {

        List<ResellerEndUser> resellerEndUserList = saveRo.getEndUsers().stream().map(endUser -> {
            ResellerEndUser resellerEndUser = new ResellerEndUser();
            resellerEndUser.setResellerId(saveRo.getId());
            resellerEndUser.setEndUserId(endUser.getId());
            resellerEndUser.setType(ResellerConstant.ResellerEndUserType.SOLD_TO);
            return resellerEndUser;
        }).collect(Collectors.toList());

        EntityMergeInfoV2<ResellerEndUser> mergeInfo = MergeEntityUtil.calculateEntityMergeInfo(
                resellerEndUserList,
                resellerEndUserService.getByResellerId(saveRo.getId(), ResellerConstant.ResellerEndUserType.SOLD_TO),
                MergeEntityOptions.<ResellerEndUser>builder().keyExtractor(ResellerEndUser::getEndUserId).build()
        );

        MergeEntityUtil.doDbMerge(mergeInfo, resellerEndUserService);
    }

    @Override
    public List<EndUser> findByCustomerNumber(Collection<String> customerNumbers) {
        return this.lambdaQuery()
                .in(EndUser::getCustomerNumber, customerNumbers)
                .list();
    }

    @Override
    public String getAccountIdByCustomNumber(String sapId) {
        return lambdaQuery()
                .eq(EndUser::getCustomerNumber, sapId)
                .oneOpt()
                .orElseThrow(() -> new BytzBootException("找不到【" + sapId + "】对应的endUser"))
                .getAccountId();
    }
}
